package com.android.quizvoctrainer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;


public class Utils {
	public final static CharSequence delimitor = ";";
	public final static CharSequence nl = "\n";
	public final static String currentListFilenameKey = "currentListFilename";
	public final static String numberOfQuestionsKey = "numberOfQuestions";
	public static QuizVocList loadCurrentListFromFile(CharSequence path, CharSequence filename) {
		QuizVocList list = new QuizVocList();
		list.setFilename(filename);
		if (path != null && filename != null) {
			StringBuffer sb = new StringBuffer("");
			String line;
			File file = new File(path + "/" + filename);
			try {
			    BufferedReader reader = new BufferedReader(new FileReader(file));
			    line = reader.readLine();
			    while(line != null)
			    {
			        sb.append(line);
			        line = reader.readLine();
			        if (line != null) sb.append(nl);
			    }
			    reader.close();
			} catch (FileNotFoundException e) {
				e.getMessage();
			} catch (IOException e) {
				e.getMessage();
			}
			MainActivity.debug(sb.toString());
			list.fromString(sb.toString());
		}
		return list;
	}
	public static void saveListToFile(QuizVocList list, CharSequence path, CharSequence filename) {
		if (path != null && filename != null) {
			try {
				File file = new File(path + "/" + filename);
				file.createNewFile();
				PrintWriter writer = new PrintWriter(file);
				writer.write(list.toString());
				writer.flush();
				writer.close();
			} catch (FileNotFoundException e) {
				e.getMessage();
			} catch (IOException e) {
				e.getMessage();
			}
		}
	}
	public static String getTxtFromGoogleDocWithGooglShortUrl(String code) {
		String fullUrl = "http://goo.gl/" + code;
		String result = "";
		BufferedReader in = null;
		try {
		    // Create a URL for the desired page
			URL url = new URL(fullUrl);
			String tmpstr = "";
	    	allowAllSSL();
	    	HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		    while ((tmpstr = in.readLine()) != null) {
		    	result = result + tmpstr + "\n";
		    }
		    in.close();
		    result = result.substring(0, result.length() - 1);
		    // parse the result to get the https url
		    result = result.substring(result.indexOf("https://"), result.indexOf("\">here"));
		    result = result.replaceAll("&amp;", "&");
		    return getTxtFromGoogleDocWithUrl(result);
		} catch (MalformedURLException e) {
			result += "\nMalformedURLException\n" + e.getMessage() + "\n" + stackToString(e.getStackTrace());
		} catch (IOException e) {
			result += "\nIOException\n" + e.getMessage() + "\n" + stackToString(e.getStackTrace());
		}	
		return result;
	}
	public static String getTxtFromGoogleDocWithId(String docId) {
		String fullUrl = "https://docs.google.com/feeds/download/documents/Export?docId=" + docId + "&exportFormat=txt&format=txt";
		return getTxtFromGoogleDocWithUrl(fullUrl);
	}
	public static String getTxtFromGoogleDocWithUrl(String fullUrl) {
		String result = "";
		BufferedReader in = null;
		try {
		    // Create a URL for the desired page
			URL url = new URL(fullUrl);
			String tmpstr = "";
	    	allowAllSSL();
			HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
		    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		    while ((tmpstr = in.readLine()) != null) {
		    	result = result + tmpstr + "\n";
		    }
		    result = result.substring(0, result.length() - 1);
		    in.close();
		} catch (MalformedURLException e) {
			result += "\nMalformedURLException\n" + e.getMessage() + "\n" + stackToString(e.getStackTrace());
		} catch (IOException e) {
			result += "\nIOException\n" + e.getMessage() + "\n" + stackToString(e.getStackTrace());
		}	
		return result;
	}
	public static String stackToString(StackTraceElement[] trace) {
		String result = "";
		for (int i=0;i<5;i++) {
			result += "\n" + trace[i].toString();
		}
		return result;
	}
    private static TrustManager[] trustManagers; 
    public static class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager { 
            private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; 
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} 
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} 
            public boolean isClientTrusted(X509Certificate[] chain) {return(true);} 
            public boolean isServerTrusted(X509Certificate[] chain) {return(true);} 
            public X509Certificate[] getAcceptedIssuers() {return(_AcceptedIssuers);} 
    } 
    public static void allowAllSSL() { 
    	javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { 
            public boolean verify ( String hostname, SSLSession session) {return true;} 
    	}); 
    	javax.net.ssl.SSLContext context=null; 
	    if(trustManagers == null) { 
	            trustManagers = new javax.net.ssl.TrustManager[]{new _FakeX509TrustManager()}; 
	    } 
	    try { 
	            context = javax.net.ssl.SSLContext.getInstance("TLS"); 
	            context.init(null, trustManagers, new SecureRandom()); 
	    } catch (NoSuchAlgorithmException e) { 
	            //Log.e("allowAllSSL", e.toString()); 
	    } catch (KeyManagementException e) { 
	            //Log.e("allowAllSSL", e.toString()); 
	    }
	    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); 
    } 
}
